import request from '@/utils/request'
import { removeTokenInfo, setTokenInfo } from '@/utils/storage'

/**
 * 获取验证码
 * @param {*} mobile 手机号
 * @returns
 */
export const sendCode = (mobile) => {
  return async () => {
    await request({
      method: 'GET',
      url: `/sms/codes/${mobile}`,
    })
  }
}

/**
 * 登录
 * @param {*} data
 * @returns
 */
export const login = (data) => {
  return async (dispatch) => {
    const { data: res } = await request({
      method: 'POST',
      url: '/authorizations',
      data,
    })
    dispatch(saveToken(res))
    setTokenInfo(res)
  }
}

/**
 * 存token
 * @param {*} token
 * @returns
 */
export const saveToken = (payload) => {
  return {
    type: 'login/saveToken',
    payload,
  }
}

/**
 * 退出登录
 * @returns
 */
export const logout = () => {
  return (dispatch) => {
    // 删除本地token
    removeTokenInfo()
    // 删除rudex中token
    dispatch({
      type: 'login/logout',
    })
  }
}
